package com.ruoyi.business.service.impl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.ruoyi.business.domain.TOrderInfo;
import com.ruoyi.business.domain.TRecipientInfo;
import com.ruoyi.business.param.MsgPayResult;
import com.ruoyi.business.response.ErrorResponseData;
import com.ruoyi.business.response.ResponseData;
import com.ruoyi.business.response.SuccessResponseData;
import com.ruoyi.business.service.BasePayment;
import com.ruoyi.business.service.ChargeService;
import com.ruoyi.common.exception.ServiceException;
import com.ruoyi.common.utils.HttpUtils;
import com.ruoyi.common.utils.MoneyUtil;
import com.ruoyi.common.utils.PhoneUtil;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.common.utils.payment.dongwopay.DongWoPayUtils;
import com.ruoyi.common.utils.payment.pbqzpay.PubuPayUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.HashMap;

@Service("dongwoPayService")
public class DongwoPayServiceImpl extends BasePayment {


    @Resource
    private ChargeService chargeService;

    @Override
    public JSONObject createPayOrder(TOrderInfo orderInfo) throws Exception {
        JSONObject jsonObject = new JSONObject();
        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        HashMap<String, String> headerMap = new HashMap();
        HashMap<String, String> dataMap = new HashMap();
//        String qrcode = userRecipientInfo.getReceiptQrcode();
//        String qrcode_ = HttpUtils.getParam(qrcode,"userAppId");
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        String token = accountObj.getString("ck");
        JSONObject  reqOrderObj  = new JSONObject(true);
        headerMap.put("Authorization","Bearer "+token);
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 appId=com.daimao.dongwo");
        //获取登录用户信息
//        String personalInfoUrl = "https://gateway.jrdaimao.com/easyhome-app-application/member/personalInfo?requestTime=1733553481755&dwSign=BA74631C32E2D4ECED33773AC8F1A5EB&dwrsv="+version;
//        logger.info("personalInfo 请求地址:{}，请求参数：{}",personalInfoUrl,reqOrderObj.toJSONString());
//        String personalInfoRes = HttpUtils.sendJsonMessage(personalInfoUrl,headerMap,reqOrderObj.toJSONString());
//        JSONObject  personalInfoResObj = JSONObject.parseObject(personalInfoRes);
//        logger.info("personalInfo 返回:{}",personalInfoResObj.toJSONString());
//
//        if(personalInfoResObj.getIntValue("code")!=200){
//            jsonObject.put("code","100");
//            jsonObject.put("msg",personalInfoResObj.getString("message"));
//            logger.info("========修改收款账号为不可用===============");
//            userRecipientInfo.setOnline(0);
//            userRecipientInfo.setDisabledInfo(personalInfoResObj.getString("message"));
//            userRecipientService.updateTRecipientInfo(userRecipientInfo);
//            return jsonObject;
//        }
        String memberId = accountObj.getString("memberId");

        String merchantId = accountObj.getString("merchantId");
        String userName = accountObj.getString("userName");
        String phone =accountObj.getString("phone");

        long time = System.currentTimeMillis();
        String version = "2.0.18";
        //获取shopid
        reqOrderObj.put("shopId","");
        
        String sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/shop/listShopSelectedApp",version,reqOrderObj);
        String getShopUrl = "https://gateway.jrdaimao.com/easyhome-app-application/shop/listShopSelectedApp?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("getShopUrl 请求地址:{}，请求参数：{}",getShopUrl,reqOrderObj.toJSONString());

        String shopRes = HttpUtils.sendJsonMessage(getShopUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  shopObj = JSONObject.parseObject(shopRes);
        logger.info("getShopUrl 返回：{}",shopObj.toJSONString());

        if(shopObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",shopObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(shopObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONArray shopArry = shopObj.getJSONArray("data");
        if(shopArry.size()==0){
            jsonObject.put("code","100");
            jsonObject.put("msg","无店铺信息");
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo("无店铺信息");
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        String shopId = ((JSONObject)shopArry.get(0)).getString("shopId");

        //注册买家信息
        
        String registphone = PhoneUtil.getPhoneNum();
        reqOrderObj  = new JSONObject(true);
        reqOrderObj.put("phone", registphone);
        reqOrderObj.put("registerType",1);
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/member/registerVirtualMember",version,reqOrderObj);
        String registMerUrl ="https://gateway.jrdaimao.com/easyhome-app-application/member/registerVirtualMember?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;

        logger.info("registMerUrl 请求地址:{}，请求参数：{}",registMerUrl,reqOrderObj.toJSONString());

        String registerVirtualMemberRes = HttpUtils.sendJsonMessage(registMerUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  registerVirtualMemberResObj = JSONObject.parseObject(registerVirtualMemberRes);
        logger.info("registMerUrl 返回：{}",registerVirtualMemberResObj.toJSONString());

        if(registerVirtualMemberResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",registerVirtualMemberResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(registerVirtualMemberResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONObject merObj = JSONObject.parseObject(registerVirtualMemberResObj.getString("data"));
        String memberVirtualId = merObj.getString("memberId");
        reqOrderObj  = new JSONObject(true);
        reqOrderObj.put("shopId", shopId);
        reqOrderObj.put("sortType",99);
        reqOrderObj.put("keyWord","");
        reqOrderObj.put("page",1);
        reqOrderObj.put("pageSize",10);
        reqOrderObj.put("categoryId",null);
        reqOrderObj.put("consumerMemberId",memberVirtualId);
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/goods/listPlaceAnOrderGoods",version,reqOrderObj);
        String goodUrl = "https://gateway.jrdaimao.com/easyhome-app-application/goods/listPlaceAnOrderGoods?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;

        logger.info("goodUrl 请求地址:{}，请求参数：{}",goodUrl,reqOrderObj.toJSONString());

        String listPlaceAnOrderGoodsRes = HttpUtils.sendJsonMessage(goodUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  listPlaceAnOrderGoodsResObj = JSONObject.parseObject(listPlaceAnOrderGoodsRes);
        logger.info("goodUrl 返回：{}",listPlaceAnOrderGoodsResObj.toJSONString());

        if(listPlaceAnOrderGoodsResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",listPlaceAnOrderGoodsResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(listPlaceAnOrderGoodsResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONArray listPlaceAnOrderGoodsList = listPlaceAnOrderGoodsResObj.getJSONObject("data").getJSONArray("list");
        if(listPlaceAnOrderGoodsList.size()==0){
            jsonObject.put("code","100");
            jsonObject.put("msg","无商品信息");
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo("无商品信息");
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        JSONObject listPlaceAnOrderGoodsObj = listPlaceAnOrderGoodsList.getJSONObject(0);

        listPlaceAnOrderGoodsObj.put("num",0);
        
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/goods/listBPortSkuByGoodsId",version,listPlaceAnOrderGoodsObj);
        String listBPortSkuByGoodsIdUrl = "https://gateway.jrdaimao.com/easyhome-app-application/goods/listBPortSkuByGoodsId?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("listBPortSkuByGoodsIdUrl 请求地址:{}，请求参数：{}",listBPortSkuByGoodsIdUrl,listPlaceAnOrderGoodsObj.toJSONString());
        String listBPortSkuByGoodsIdRes = HttpUtils.sendJsonMessage(listBPortSkuByGoodsIdUrl,headerMap,listPlaceAnOrderGoodsObj.toJSONString());
        JSONObject  listBPortSkuByGoodsIdResObj = JSONObject.parseObject(listBPortSkuByGoodsIdRes);
        logger.info("listBPortSkuByGoodsIdUrl 返回：{}",listBPortSkuByGoodsIdResObj.toJSONString());

        if(listBPortSkuByGoodsIdResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",listBPortSkuByGoodsIdResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(listBPortSkuByGoodsIdResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        String goodsSkuId = ((JSONObject)listBPortSkuByGoodsIdResObj.getJSONArray("data").get(0)).getString("goodsSkuId");
        JSONArray standardValues = ((JSONObject)listBPortSkuByGoodsIdResObj.getJSONArray("data").get(0)).getJSONArray("standardValues");
        String goodsPrice = ((JSONObject)listBPortSkuByGoodsIdResObj.getJSONArray("data").get(0)).getString("goodsPrice");
        int goodsStock = listBPortSkuByGoodsIdResObj.getIntValue("goodsStock");
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/goods/queryCategoryDialog",version,listPlaceAnOrderGoodsObj);
        String queryCategoryDialogUrl ="https://gateway.jrdaimao.com/easyhome-app-application/goods/queryCategoryDialog?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("queryCategoryDialogUrl 请求地址:{}，请求参数：{}",queryCategoryDialogUrl,listPlaceAnOrderGoodsObj.toJSONString());

        String queryCategoryDialogRes = HttpUtils.sendJsonMessage(queryCategoryDialogUrl,headerMap,listPlaceAnOrderGoodsObj.toJSONString());
        JSONObject  queryCategoryDialogResObj = JSONObject.parseObject(queryCategoryDialogRes);
        logger.info("queryCategoryDialogUrl 返回：{}",queryCategoryDialogUrl,queryCategoryDialogResObj.toJSONString());

        if(queryCategoryDialogResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",queryCategoryDialogResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(queryCategoryDialogResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        reqOrderObj  = new JSONObject(true);
        reqOrderObj.put("shopId", shopId);
        reqOrderObj.put("deliveryType", "1");
        reqOrderObj.put("boothId", null);
        JSONArray shopOrderGoodsDetailsList = new JSONArray();
        listPlaceAnOrderGoodsObj.put("num",1);
        listPlaceAnOrderGoodsObj.put("shopId",shopId);
        listPlaceAnOrderGoodsObj.put("minGoodsPrice",listPlaceAnOrderGoodsObj.getFloatValue("goodsMinPrice"));
        listPlaceAnOrderGoodsObj.put("maxGoodsPrice",listPlaceAnOrderGoodsObj.getFloatValue("goodsMaxPrice"));
        listPlaceAnOrderGoodsObj.put("standards",queryCategoryDialogResObj.getJSONObject("data").getJSONArray("standards"));

        listPlaceAnOrderGoodsObj.put("merchantId",merchantId);
        listPlaceAnOrderGoodsObj.put("price",goodsPrice);
        listPlaceAnOrderGoodsObj.put("skuId",goodsSkuId);
        listPlaceAnOrderGoodsObj.put("properties",standardValues);
        listPlaceAnOrderGoodsObj.put("hold",goodsStock);

        ArrayList<String> skuStrList = new ArrayList<>();

        String standardName = ((JSONObject)listPlaceAnOrderGoodsObj.getJSONArray("standards").get(0)).getString("standardName");
        String standardValueName = ((JSONObject)standardValues.get(0)).getString("standardValueName");
        skuStrList.add(standardName+":"+standardValueName);
        listPlaceAnOrderGoodsObj.put("skuStr",skuStrList);
        listPlaceAnOrderGoodsObj.put("goodsSkuId",goodsSkuId);
        listPlaceAnOrderGoodsObj.put("goodsNum",1);
        listPlaceAnOrderGoodsObj.put("goodsPrice",goodsPrice);
        shopOrderGoodsDetailsList.add(listPlaceAnOrderGoodsObj);
        reqOrderObj.put("shopOrderGoodsDetailsList",shopOrderGoodsDetailsList);
        reqOrderObj.put("shopGuideId", memberId);
        reqOrderObj.put("shopGuideName", userName);
        reqOrderObj.put("shopGuidePhone", phone);
        reqOrderObj.put("acMemberId", "");
        reqOrderObj.put("isMember", 1);
        reqOrderObj.put("memberId", memberVirtualId);
        reqOrderObj.put("buyerPhone", registphone);
        reqOrderObj.put("phone", registphone);
        reqOrderObj.put("deviceSource", "h5Business");
        reqOrderObj.put("apiVersion", "2.1.6");
        reqOrderObj.put("contractType", "1");

        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/b/shop/order/orderConfirmBySeller",version,reqOrderObj);

        String orderConfirmBySellerUrl ="https://gateway.jrdaimao.com/easyhome-app-application/b/shop/order/orderConfirmBySeller?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("orderConfirmBySellerUrl 请求地址:{}，请求参数：{}",orderConfirmBySellerUrl,reqOrderObj.toJSONString());

        String orderConfirmBySellerRes = HttpUtils.sendJsonMessage(orderConfirmBySellerUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  orderConfirmBySellerResObj = JSONObject.parseObject(orderConfirmBySellerRes);
        logger.info("orderConfirmBySellerUrl 返回：{}",orderConfirmBySellerResObj.toJSONString());

        if(orderConfirmBySellerResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",orderConfirmBySellerResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(orderConfirmBySellerResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }

        reqOrderObj  = new JSONObject(true);
        JSONArray goods = new JSONArray();
        JSONObject goodObj = new JSONObject();
        goodObj.put("goodsId",listPlaceAnOrderGoodsObj.getString("goodsId"));
        goodObj.put("num",1);
        goodObj.put("goodsPrice",goodsPrice);
        goods.add(goodObj);
        reqOrderObj.put("goods",goods);
        reqOrderObj.put("phone",registphone);
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/mini/order/getDiscountPrice",version,reqOrderObj);
        String getDiscountPriceUrl ="https://gateway.jrdaimao.com/easyhome-app-application/mini/order/getDiscountPrice?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;

        logger.info("getDiscountPriceUrl 请求地址:{}，请求参数：{}",getDiscountPriceUrl,reqOrderObj.toJSONString());

        String getDiscountPriceRes = HttpUtils.sendJsonMessage(getDiscountPriceUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  getDiscountPriceResObj = JSONObject.parseObject(getDiscountPriceRes);
        logger.info("getDiscountPriceUrl 返回{}",getDiscountPriceResObj.toJSONString());

        if(getDiscountPriceResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",getDiscountPriceResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(getDiscountPriceResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }

        /**
         * {
         * 	"shopId": "1021233472930324480",
         * 	"shopOrderGoodsDetailsList": [{
         * 		"goodsSkuId": "1022352147997777920",
         * 		"shopId": "1021233472930324480",
         * 		"goodsCode": "0000000202372335",
         * 		"goodsId": "1022352147939057664",
         * 		"goodsSkuTitle": "得高 地板 实木地板",
         * 		"goodsTitle": "得高 地板 实木地板",
         * 		"goodsPrice": "558.84",
         * 		"goodsPic": "iOS/Resources/25D2E896-67F4-4B67-A9B8-ED7DF5A2A908-1732859323687_829x1007.jpg",
         * 		"goodsPicUrl": "https://ossprod.jrdaimao.com/iOS/Resources/25D2E896-67F4-4B67-A9B8-ED7DF5A2A908-1732859323687_829x1007.jpg",
         * 		"deliveryTime": null,
         * 		"goodsNum": 1,
         * 		"skillGoods": false,
         * 		"skillPrice": null,
         * 		"skillOrgPrice": "599",
         * 		"equityTagsMap": null,
         * 		"realPrice": "599",
         * 		"num": 1,
         * 		"price": "558.84",
         * 		"needCalSkillGoods": false
         * 	    }],
         * 	"acMemberId": "",
         * 	"isMember": 1,
         * 	"memberId": "1025320902105300992",
         * 	"buyerPhone": "15368845408",
         * 	"phone": "15368845408",
         * 	"deviceSource": "h5Business",
         * 	"apiVersion": "2.1.6"
         * }
         */
        reqOrderObj  = new JSONObject(true);
        reqOrderObj.put("shopId", shopId);
        shopOrderGoodsDetailsList = new JSONArray();
//        JSONObject shopOrderGoodsDetailObj = new JSONObject();
//        shopOrderGoodsDetailObj.put("num",1);
//        shopOrderGoodsDetailObj.put("price",new BigDecimal(MoneyUtil.fenToYuan(orderInfo.getMoney()+"")).setScale(2));
//        shopOrderGoodsDetailObj.put("needCalSkillGoods",false);
//        shopOrderGoodsDetailObj.put("goodsSkuId",goodsSkuId);
//        shopOrderGoodsDetailObj.put("shopId",shopId);
//        shopOrderGoodsDetailObj.put("goodsCode",listPlaceAnOrderGoodsObj.getString("goodsCode"));
//        shopOrderGoodsDetailObj.put("goodsId",listPlaceAnOrderGoodsObj.getString("goodsId"));
//        shopOrderGoodsDetailObj.put("goodsSkuTitle",listPlaceAnOrderGoodsObj.getString("goodsTitle"));
//        shopOrderGoodsDetailObj.put("goodsTitle",listPlaceAnOrderGoodsObj.getString("goodsTitle"));
//
//        shopOrderGoodsDetailObj.put("goodsPrice",new BigDecimal(MoneyUtil.fenToYuan(orderInfo.getMoney()+"")).setScale(2));
//        shopOrderGoodsDetailObj.put("goodsPic",listPlaceAnOrderGoodsObj.getString("goodsMainPic").replace("https://ossprod.jrdaimao.com/",""));
//        shopOrderGoodsDetailObj.put("goodsPicUrl",listPlaceAnOrderGoodsObj.getString("goodsMainPic"));
//
//        shopOrderGoodsDetailObj.put("deliveryTime",null);
//        shopOrderGoodsDetailObj.put("goodsNum",1);
//        shopOrderGoodsDetailObj.put("skillGoods",false);
//        shopOrderGoodsDetailObj.put("skillPrice",null);
//        shopOrderGoodsDetailObj.put("skillOrgPrice",goodsPrice);
//        shopOrderGoodsDetailObj.put("equityTagsMap",null);
//        shopOrderGoodsDetailObj.put("realPrice",goodsPrice);
        listPlaceAnOrderGoodsObj.put("skillPrice",null);
        listPlaceAnOrderGoodsObj.put("skillGoods",false);
        shopOrderGoodsDetailsList.add(listPlaceAnOrderGoodsObj);
        reqOrderObj.put("shopOrderGoodsDetailsList",shopOrderGoodsDetailsList);
        reqOrderObj.put("acMemberId", "");
        reqOrderObj.put("isMember", 1);
        reqOrderObj.put("memberId", memberVirtualId);
        reqOrderObj.put("buyerPhone", registphone);
        reqOrderObj.put("phone", registphone);
        reqOrderObj.put("deviceSource", "h5Business");
        reqOrderObj.put("apiVersion", "2.1.6");
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/b/shop/order/orderConfirmBySeller",version,reqOrderObj);
        orderConfirmBySellerUrl ="https://gateway.jrdaimao.com/easyhome-app-application/b/shop/order/orderConfirmBySeller?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("修改价格后 orderConfirmBySellerUrl 请求地址:{}，请求参数：{}",orderConfirmBySellerUrl,reqOrderObj.toJSONString());

        orderConfirmBySellerRes = HttpUtils.sendJsonMessage(orderConfirmBySellerUrl,headerMap,reqOrderObj.toJSONString());
        orderConfirmBySellerResObj = JSONObject.parseObject(orderConfirmBySellerRes);
        logger.info("修改价格后 orderConfirmBySellerUrl 返回：{}",orderConfirmBySellerResObj.toJSONString());

        if(orderConfirmBySellerResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",orderConfirmBySellerResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(orderConfirmBySellerResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        //获取新的daohang
        reqOrderObj = new JSONObject(true);
        reqOrderObj.put("shopId",shopId);
        reqOrderObj.put("actionType","queryShopGuideBasicUser");
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/member/queryMerchantUserRoleByShop",version,reqOrderObj);
        String queryMerchantUserRoleByShopUrl = "https://gateway.jrdaimao.com/easyhome-app-application/member/queryMerchantUserRoleByShop?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;

        logger.info("修改价格后 queryMerchantUserRoleByShopUrl 请求地址:{}，请求参数：{}",queryMerchantUserRoleByShopUrl,reqOrderObj.toJSONString());

        String queryMerchantUserRoleByShopRes = HttpUtils.sendJsonMessage(queryMerchantUserRoleByShopUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject queryMerchantUserRoleByShopResObj = JSONObject.parseObject(queryMerchantUserRoleByShopRes);
        logger.info("修改价格后 queryMerchantUserRoleByShopUrl 返回：{}",queryMerchantUserRoleByShopResObj.toJSONString());

        if(queryMerchantUserRoleByShopResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",queryMerchantUserRoleByShopResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(queryMerchantUserRoleByShopResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }

        String userId = ((JSONObject)queryMerchantUserRoleByShopResObj.getJSONArray("data").get(0)).getString("userId");


        reqOrderObj  = new JSONObject(true);
        reqOrderObj.put("shopId", shopId);
        shopOrderGoodsDetailsList = new JSONArray();
        JSONObject shopOrderGoodsDetailObj = new JSONObject();
        shopOrderGoodsDetailObj.put("goodsSkuId",goodsSkuId);
        shopOrderGoodsDetailObj.put("shopId",shopId);
        shopOrderGoodsDetailObj.put("goodsCode",listPlaceAnOrderGoodsObj.getString("goodsCode"));
        shopOrderGoodsDetailObj.put("goodsId",listPlaceAnOrderGoodsObj.getString("goodsId"));
        shopOrderGoodsDetailObj.put("goodsSkuTitle",listPlaceAnOrderGoodsObj.getString("goodsTitle"));
        shopOrderGoodsDetailObj.put("goodsTitle",listPlaceAnOrderGoodsObj.getString("goodsTitle"));

        shopOrderGoodsDetailObj.put("goodsPrice",new BigDecimal(MoneyUtil.fenToYuan(orderInfo.getMoney()+"")).setScale(2).toString());
        shopOrderGoodsDetailObj.put("goodsPic",listPlaceAnOrderGoodsObj.getString("goodsMainPic").replace("https://ossprod.jrdaimao.com/",""));
        shopOrderGoodsDetailObj.put("goodsPicUrl",listPlaceAnOrderGoodsObj.getString("goodsMainPic"));

        shopOrderGoodsDetailObj.put("deliveryTime",null);
        shopOrderGoodsDetailObj.put("goodsNum",1);
        shopOrderGoodsDetailObj.put("skillGoods",false);
        shopOrderGoodsDetailObj.put("skillPrice",null);
        shopOrderGoodsDetailObj.put("skillOrgPrice",goodsPrice);
        shopOrderGoodsDetailObj.put("equityTagsMap",null);
        shopOrderGoodsDetailObj.put("realPrice",goodsPrice);
        shopOrderGoodsDetailObj.put("num",1);
        shopOrderGoodsDetailObj.put("price",new BigDecimal(MoneyUtil.fenToYuan(orderInfo.getMoney()+"")).setScale(2));
        shopOrderGoodsDetailObj.put("needCalSkillGoods",false);
        shopOrderGoodsDetailsList.add(shopOrderGoodsDetailObj);
        reqOrderObj.put("shopOrderGoodsDetailsList",shopOrderGoodsDetailsList);
        reqOrderObj.put("acMemberId", "");
        reqOrderObj.put("isMember", 1);
        reqOrderObj.put("memberId", memberVirtualId);
        reqOrderObj.put("buyerPhone", registphone);
        reqOrderObj.put("phone", registphone);
        reqOrderObj.put("deviceSource", "h5Business");
        reqOrderObj.put("apiVersion", "2.1.6");
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/b/shop/order/orderConfirmBySeller",version,reqOrderObj);
        orderConfirmBySellerUrl ="https://gateway.jrdaimao.com/easyhome-app-application/b/shop/order/orderConfirmBySeller?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("修改价格后 orderConfirmBySellerUrl 请求地址:{}，请求参数：{}",orderConfirmBySellerUrl,reqOrderObj.toJSONString());

        orderConfirmBySellerRes = HttpUtils.sendJsonMessage(orderConfirmBySellerUrl,headerMap,reqOrderObj.toJSONString());
        orderConfirmBySellerResObj = JSONObject.parseObject(orderConfirmBySellerRes);
        logger.info("修改价格后 orderConfirmBySellerUrl 返回：{}",orderConfirmBySellerResObj.toJSONString());

        if(orderConfirmBySellerResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",orderConfirmBySellerResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(orderConfirmBySellerResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }


        reqOrderObj  = new JSONObject(true);
        goods = new JSONArray();
        goodObj = new JSONObject(true);
        goodObj.put("goodsId",listPlaceAnOrderGoodsObj.getString("goodsId"));
        goodObj.put("num",1);
        goodObj.put("goodsPrice",new BigDecimal(MoneyUtil.fenToYuan(orderInfo.getMoney()+"")).setScale(2));
        goods.add(goodObj);
        reqOrderObj.put("goods",goods);
        reqOrderObj.put("phone",registphone);
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/mini/order/getDiscountPrice",version,reqOrderObj);
        getDiscountPriceUrl ="https://gateway.jrdaimao.com/easyhome-app-application/mini/order/getDiscountPrice?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("getDiscountPriceUrl 请求地址:{}，请求参数：{}",getDiscountPriceUrl,reqOrderObj.toJSONString());

        getDiscountPriceRes = HttpUtils.sendJsonMessage(getDiscountPriceUrl,headerMap,reqOrderObj.toJSONString());
        getDiscountPriceResObj = JSONObject.parseObject(getDiscountPriceRes);
        logger.info("getDiscountPriceUrl 返回{}",getDiscountPriceResObj.toJSONString());

        if(getDiscountPriceResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",getDiscountPriceResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(getDiscountPriceResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
       String reciName = PhoneUtil.randomName(true,2);
        reqOrderObj  = new JSONObject(true);
        LocalDate today = LocalDate.now(); // 获取今天的日期
        LocalDate dayAfterTomorrow = today.plusDays(1);

        String deliveryTime = dayAfterTomorrow.format(DateTimeFormatter.ofPattern("yyyy-MM-dd"));
//        reqOrderObj.put("pickupName", reciName);
        //deliveryAddressId
        reqOrderObj.put("pickupName", "");
        reqOrderObj.put("pickupPhone", registphone);
//        reqOrderObj.put("deliveryAddressId", "");
        reqOrderObj.put("deliveryType", "1");
        reqOrderObj.put("campaignIds", new JSONArray());
        reqOrderObj.put("shopGuideId", userId);
        reqOrderObj.put("shopGuideName", userName);
        reqOrderObj.put("shopGuidePhone", phone);
        shopOrderGoodsDetailsList = new JSONArray();
        shopOrderGoodsDetailObj = new JSONObject();
        shopOrderGoodsDetailObj.put("deliveryTime",deliveryTime);
        shopOrderGoodsDetailObj.put("goodsId",listPlaceAnOrderGoodsObj.getString("goodsId"));
        shopOrderGoodsDetailObj.put("goodsSkuId",goodsSkuId);
        shopOrderGoodsDetailObj.put("shopId",shopId);
        shopOrderGoodsDetailObj.put("goodsCode",listPlaceAnOrderGoodsObj.getString("goodsCode"));
        shopOrderGoodsDetailObj.put("goodsSkuTitle",listPlaceAnOrderGoodsObj.getString("goodsTitle"));
        shopOrderGoodsDetailObj.put("goodsTitle",listPlaceAnOrderGoodsObj.getString("goodsTitle"));
        shopOrderGoodsDetailObj.put("goodsPrice",new BigDecimal(MoneyUtil.fenToYuan(orderInfo.getMoney()+"")).setScale(2));
        shopOrderGoodsDetailObj.put("goodsPic",listPlaceAnOrderGoodsObj.getString("goodsMainPic").replace("https://ossprod.jrdaimao.com/",""));
        shopOrderGoodsDetailObj.put("goodsPicUrl",listPlaceAnOrderGoodsObj.getString("goodsMainPic"));
        shopOrderGoodsDetailObj.put("goodsNum",1);
        shopOrderGoodsDetailObj.put("skillGoods",false);
        shopOrderGoodsDetailObj.put("skillPrice",null);
        shopOrderGoodsDetailObj.put("skillOrgPrice",goodsPrice);
        shopOrderGoodsDetailObj.put("equityTagsMap",null);
        shopOrderGoodsDetailObj.put("realPrice",new BigDecimal(MoneyUtil.fenToYuan(orderInfo.getMoney()+"")).setScale(2));
        shopOrderGoodsDetailObj.put("needCalSkillGoods",false);
        shopOrderGoodsDetailsList.add(shopOrderGoodsDetailObj);
        reqOrderObj.put("goodsDetailsList",shopOrderGoodsDetailsList);
        reqOrderObj.put("dmcouponIdSet", new JSONArray());
        reqOrderObj.put("acMemberId", "");
        reqOrderObj.put("isMember", 1);
        reqOrderObj.put("memberId", memberVirtualId);
        reqOrderObj.put("phone", registphone);
        reqOrderObj.put("linkedCampaignId", "");
        reqOrderObj.put("useVCards", new JSONArray());
        reqOrderObj.put("redCouponIdSet",new JSONArray());
        reqOrderObj.put("registerFlag",false);
        reqOrderObj.put("deliveryTime",deliveryTime);
        reqOrderObj.put("usePump",false);
        reqOrderObj.put("orderPumpMoney","");
        reqOrderObj.put("validateCode","");
        reqOrderObj.put("selectEasyWorker",false);
        reqOrderObj.put("deviceSource", "h5Business");
        reqOrderObj.put("apiVersion", "2.1.6");
        reqOrderObj.put("engineeringOrder", false);
        reqOrderObj.put("contractType",1);
        time = System.currentTimeMillis();
        sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/shop/order/addShopOrderListBySeller",version,reqOrderObj);
        String addShopOrderListBySellerUrl = "https://gateway.jrdaimao.com/easyhome-app-application/shop/order/addShopOrderListBySeller?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;

        logger.info("修改价格后 addShopOrderListBySellerUrl 请求地址:{}，请求参数：{}",addShopOrderListBySellerUrl,JSONObject.toJSONString(reqOrderObj));
        String addShopOrderListBySellerUrlRes = HttpUtils.sendJsonMessage(addShopOrderListBySellerUrl,headerMap,JSONObject.toJSONString(reqOrderObj, SerializerFeature.WriteMapNullValue));
        JSONObject addShopOrderListBySellerUrlResObj = JSONObject.parseObject(addShopOrderListBySellerUrlRes);
        logger.info("修改价格后 addShopOrderListBySellerUrl 返回：{}",addShopOrderListBySellerUrlResObj.toJSONString());

        if(addShopOrderListBySellerUrlResObj.getIntValue("code")!=200){
            jsonObject.put("code","100");
            jsonObject.put("msg",addShopOrderListBySellerUrlResObj.getString("message"));
            logger.info("========修改收款账号为不可用===============");
            userRecipientInfo.setOnline(0);
            userRecipientInfo.setDisabledInfo(addShopOrderListBySellerUrlResObj.getString("message"));
            userRecipientService.updateTRecipientInfo(userRecipientInfo);
            return jsonObject;
        }
        String orderId = addShopOrderListBySellerUrlResObj.getJSONObject("data").getString("orderId");
        jsonObject.put("payUrl","alipays://platformapi/startapp?appId=2021004105652035&page=pages/pay/pages/outsidePay/index&query=oi="+orderId);
        jsonObject.put("orderNo",orderId);
        jsonObject.put("code","200");
        return jsonObject;

    }


    public JSONObject createWxPayOrder(TOrderInfo orderInfo) throws ServiceException, UnsupportedEncodingException {
        return null;
    }



    private TRecipientInfo reLogin(TRecipientInfo tRecipientInfo) {
        long time = System.currentTimeMillis();
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        JSONObject  loginObj  = new JSONObject();
        loginObj.put("pwd",accountObj.getString("password"));
        loginObj.put("userName",tRecipientInfo.getChannelAccount());
        String sign = PubuPayUtils.getSign(time,loginObj,"");
        String loginUrl = "http://api.openpubu.com/open/login?token=&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
        String loginRes = HttpUtils.sendJsonMessage(loginUrl,headerMap,loginObj.toJSONString());
        JSONObject  loginResObj = JSONObject.parseObject(loginRes);
        if(loginResObj.getIntValue("status")!=200){
            return tRecipientInfo;
        }
        JSONObject userObj = (JSONObject)loginResObj.getJSONObject("body").getJSONArray("userList").get(0);

        String token = userObj.getString("token");
        accountObj.put("token",token);
        tRecipientInfo.setAccountJson(accountObj.toJSONString());
        tRecipientInfo.setOnline(1);
        userRecipientService.updateTRecipientInfo(tRecipientInfo);
        return tRecipientInfo;
    }

    private JSONObject reSubmit(TRecipientInfo tRecipientInfo,JSONObject  reqOrderObj) {
        long time = System.currentTimeMillis();
        String accountJson = tRecipientInfo.getAccountJson();
        JSONObject  accountObj = JSONObject.parseObject(accountJson);
        HashMap<String, String> headerMap = new HashMap();
        String token = accountObj.getString("token");
        String sign = PubuPayUtils.getSign(time,reqOrderObj,token);
        String submitPayUrl = "http://api.openpubu.com/order/submitFtfpayOrder?token="+token+"&time="+time+"&sign="+sign+"&client_channel=2&api_version=2.2.5";
        String submitPayRes = HttpUtils.sendJsonMessage(submitPayUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  submitPayResObj = JSONObject.parseObject(submitPayRes);
        return submitPayResObj;
    }

    @Override
    public ResponseData smartReissueOrder(TOrderInfo orderInfo) throws Exception {
        if (StringUtils.isBlank(orderInfo.getPay3rdOrderNo())) {
            return new ErrorResponseData("未获取到三方订单号");
        }

        TRecipientInfo userRecipientInfo = userRecipientService.selectTRecipientInfoById(orderInfo.getRecipientId());
        String accountJson = userRecipientInfo.getAccountJson();
        JSONObject accountObj = JSONObject.parseObject(accountJson);
        String token = accountObj.getString("ck");
        HashMap<String, String> headerMap = new HashMap();
        headerMap.put("Authorization","Bearer "+token);
        headerMap.put("User-Agent","Mozilla/5.0 (iPhone; CPU iPhone OS 17_7_1 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Mobile/15E148 appId=com.daimao.dongwo");
        JSONObject  reqOrderObj  = new JSONObject(true);
        long time = System.currentTimeMillis();
        String version = "2.0.18";
        //获取shopid
        reqOrderObj.put("payAmount",MoneyUtil.fenToYuan(orderInfo.getMoney()+""));
        reqOrderObj.put("orderId",orderInfo.getPay3rdOrderNo());
        String sign = DongWoPayUtils.getSign(time,"/easyhome-app-application/shop/order/assignOrderStatus",version,reqOrderObj);
        String qryOrderUrl = "https://gateway.jrdaimao.com/easyhome-app-application/shop/order/assignOrderStatus?requestTime="+time+"&dwSign="+sign+"&dwrsv="+version;
        logger.info("查单 请求地址:{}，请求参数：{}",qryOrderUrl,reqOrderObj.toJSONString());

        String qryOrderRes = HttpUtils.sendJsonMessage(qryOrderUrl,headerMap,reqOrderObj.toJSONString());
        JSONObject  qryOrderResObj = JSONObject.parseObject(qryOrderRes);
        logger.info("qryOrderUrl 返回：{}",qryOrderResObj.toJSONString());
        if(qryOrderResObj.getIntValue("code")==200){
            if(qryOrderResObj.getBooleanValue("data")){
                MsgPayResult msgPayResult = new MsgPayResult();
                msgPayResult.setChannel(orderInfo.getChannel());
                msgPayResult.setTradeNo(orderInfo.getId().toString());
                msgPayResult.setChannelAccount(userRecipientInfo.getChannelAccount());
                msgPayResult.setOrderId(orderInfo.getPay3rdOrderNo());
                msgPayResult.setRealMoney(MoneyUtil.fenToYuan(orderInfo.getMoney() + ""));
                msgPayResult.setUid(userRecipientInfo.getUserId().toString());
                msgPayResult.setChannelPayMsgResult(qryOrderResObj.toJSONString());
                ResponseData responseData = chargeService.updateOrderPayResult(true, orderInfo.getId(), msgPayResult, false);
                chargeService.notifyUserPaySucc(orderInfo.getId());
                logger.info("洞窝订单回调..订单号：" + orderInfo.getId() + " 金额：" + orderInfo.getMoney() + " 处理结果：{}", responseData.getSuccess());
            }
        }
        return new SuccessResponseData();
    }
}
